package com.ubing.boot.notesforjava.config;

import com.ubing.boot.notesforjava.domel.entity.UserInfo;
import com.ubing.boot.notesforjava.utils.ThreadLocalUtils;
import org.apache.ibatis.executor.parameter.ParameterHandler;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.reflection.DefaultReflectorFactory;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;


import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Properties;

@Intercepts({
        @Signature(type= StatementHandler.class,method="prepare",args={Connection.class,Integer.class})
})

public class SqlInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
        UserInfo userInfo = ThreadLocalUtils.get();
        System.out.println(userInfo);
        System.out.println(Thread.currentThread().getName());
//        Connection connection = (Connection) invocation.getArgs()[0];
//        Object[] args = invocation.getArgs();
        MetaObject metaObject = MetaObject.forObject(statementHandler, SystemMetaObject.DEFAULT_OBJECT_FACTORY, SystemMetaObject.DEFAULT_OBJECT_WRAPPER_FACTORY, new DefaultReflectorFactory());
//
        String sql = statementHandler.getBoundSql().getSql();
//        System.out.println(sql);
        ParameterHandler parameterHandler = (ParameterHandler) metaObject.getValue("delegate.parameterHandler");
        Object parameterObject = parameterHandler.getParameterObject();
        System.out.println(parameterObject);
//        PreparedStatement preparedStatement = connection.prepareStatement(sql);
//        parameterHandler.setParameters(preparedStatement);
//        // 修改参数
        System.out.println(metaObject.getValue("delegate.boundSql.sql"));

//        metaObject.setValue("delegate.boundSql.sql",sql + " PARTITION (p_1,p_2)");
//        resultSet.close();
//        preparedStatement.close();
//        System.out.println(resultSet);
//        connection.prepareStatement()
        System.out.println(123);
//        Object proceed =
        return invocation.proceed();
    }

//    @Override
//    public Object plugin(Object target) {
//        // targer 目标对象  Interceptor 拦截器对象
//        return Plugin.wrap(target, this);
//    }
//
//    @Override
//    public void setProperties(Properties properties) {
//        // 读取是xml文件的
//        Interceptor.super.setProperties(properties);
//    }
}
